<template>
  <div class="dashboard">
    <a-row :gutter="16">
      <a-col :span="6">
        <a-card>
          <statistic
            title="在线设备"
            :value="stats.onlineDevices"
            :precision="0"
          >
            <template #prefix>
              <desktop-outlined />
            </template>
          </statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <statistic
            title="今日消息"
            :value="stats.todayMessages"
            :precision="0"
          >
            <template #prefix>
              <message-outlined />
            </template>
          </statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <statistic
            title="活跃用户"
            :value="stats.activeUsers"
            :precision="0"
          >
            <template #prefix>
              <user-outlined />
            </template>
          </statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <statistic
            title="机器码使用率"
            :value="stats.robotCodeUsage"
            :precision="2"
            suffix="%"
          >
            <template #prefix>
              <key-outlined />
            </template>
          </statistic>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="16" style="margin-top: 16px">
      <a-col :span="12">
        <a-card title="消息统计">
          <div ref="messageChart" style="height: 300px"></div>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card title="设备活跃度">
          <div ref="deviceChart" style="height: 300px"></div>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="16" style="margin-top: 16px">
      <a-col :span="24">
        <a-card title="最近消息">
          <a-table
            :columns="columns"
            :data-source="messages"
            :pagination="{ pageSize: 5 }"
          />
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { Statistic } from 'ant-design-vue'
import {
  DesktopOutlined,
  MessageOutlined,
  UserOutlined,
  KeyOutlined
} from '@ant-design/icons-vue'
import * as echarts from 'echarts'
import { getStats, getMessages, getMessageStats, getDeviceStats } from '@/api/dashboard'

const messageChart = ref(null)
const deviceChart = ref(null)
let messageChartInstance = null
let deviceChartInstance = null

const stats = ref({
  onlineDevices: 0,
  todayMessages: 0,
  activeUsers: 0,
  robotCodeUsage: 0
})

const messages = ref([])

const columns = [
  {
    title: '机器码',
    dataIndex: 'robotId',
    key: 'robotId'
  },
  {
    title: '消息类型',
    dataIndex: 'type',
    key: 'type'
  },
  {
    title: '内容',
    dataIndex: 'content',
    key: 'content'
  },
  {
    title: '时间',
    dataIndex: 'createTime',
    key: 'createTime'
  }
]

const initCharts = () => {
  messageChartInstance = echarts.init(messageChart.value)
  deviceChartInstance = echarts.init(deviceChart.value)
  
  // 消息统计图表配置
  const messageOption = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['总消息数', '成功数', '失败数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '总消息数',
        type: 'line',
        data: []
      },
      {
        name: '成功数',
        type: 'line',
        data: []
      },
      {
        name: '失败数',
        type: 'line',
        data: []
      }
    ]
  }

  // 设备活跃度图表配置
  const deviceOption = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['活跃设备', '在线率']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: []
    },
    yAxis: [
      {
        type: 'value',
        name: '设备数',
        position: 'left'
      },
      {
        type: 'value',
        name: '在线率',
        position: 'right',
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '活跃设备',
        type: 'bar',
        data: []
      },
      {
        name: '在线率',
        type: 'line',
        yAxisIndex: 1,
        data: []
      }
    ]
  }

  messageChartInstance.setOption(messageOption)
  deviceChartInstance.setOption(deviceOption)
}

const fetchData = async () => {
  try {
    const [statsRes, messageStatsRes, deviceStatsRes, messagesRes] = await Promise.all([
      getStats(),
      getMessageStats({ days: 7 }),
      getDeviceStats({ days: 7 }),
      getMessages({ limit: 5 })
    ])

    // 更新统计数据
    stats.value = statsRes.data

    // 更新消息列表
    messages.value = messagesRes.data

    // 更新消息统计图表
    const messageData = messageStatsRes.data
    messageChartInstance.setOption({
      xAxis: {
        data: messageData.map(item => item.date)
      },
      series: [
        {
          data: messageData.map(item => item.totalCount)
        },
        {
          data: messageData.map(item => item.successCount)
        },
        {
          data: messageData.map(item => item.failCount)
        }
      ]
    })

    // 更新设备活跃度图表
    const deviceData = deviceStatsRes.data
    deviceChartInstance.setOption({
      xAxis: {
        data: deviceData.map(item => item.date)
      },
      series: [
        {
          data: deviceData.map(item => item.activeCount)
        },
        {
          data: deviceData.map(item => item.onlineRate)
        }
      ]
    })
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

// 添加定时刷新
let refreshTimer = null

onMounted(() => {
  initCharts()
  fetchData()
  window.addEventListener('resize', handleResize)
  refreshTimer = setInterval(fetchData, 60000) // 每分钟刷新一次
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  messageChartInstance?.dispose()
  deviceChartInstance?.dispose()
  clearInterval(refreshTimer)
})

const handleResize = () => {
  messageChartInstance?.resize()
  deviceChartInstance?.resize()
}
</script>

<style scoped>
.dashboard {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100%;
}
</style> 